<?
define("DBD_DS", DIRECTORY_SEPARATOR);
define("DBD_MVC_DIR", dirname(__FILE__).DBD_DS);
define("DBD_SMARTY_DIR", DBD_MVC_DIR."Smarty-2.6.18".DBD_DS."libs".DBD_DS);
define("DBD_XAJAX_DIR", DBD_MVC_DIR."xajax_0.2.5".DBD_DS);

require_once("lib/dbdLoader.php");

dbdLoader::addPath(DBD_MVC_DIR);
dbdLoader::addPath(DBD_MVC_DIR."lib");
dbdLoader::addPath(DBD_SMARTY_DIR);
dbdLoader::addPath(DBD_XAJAX_DIR);

class dbdMVC
{
	const VERSION = "1.0";

	private static $instance = null;
	private static $start = null;
	private static $expose_php_info = null;
	private $app_name = null;
	private $app_dir = null;
	private $dispatcher = null;

	private function __construct()
	{
		set_exception_handler(array("dbdMVC", "e"));
		$this->setAppName("dbdMVC v".dbdMVC::VERSION);
	}

	private function init()
	{
		$router = new dbdRouter(new dbdRequest());
		$this->dispatcher = new dbdDispatcher($router, $this->app_dir);
		dbdLoader::addPath($this->app_dir);
		dbdLoader::addPath($this->app_dir.dbdLoader::getControllerDir());
		dbdLoader::addPath($this->app_dir.dbdLoader::getModelDir());
	}

	private function dispatch()
	{
		$this->dispatcher->dispatch();
	}

	private function setAppName($app_name)
	{
		$this->app_name = $app_name;
	}

	private function setAppDir($app_dir)
	{
		if (substr($app_dir, -1) != DBD_DS)
			$app_dir .= DBD_DS;
		$this->app_dir = $app_dir;
	}

	public static function getInstance()
	{
		if (self::$instance === null)
			self::$instance = new self();
		return self::$instance;
	}

	public static function e(Exception $e)
	{
		error_log($e->getMessage());
		echo nl2br($e);
	}

	public static function run($app_dir, $app_name = null)
	{
		self::$start = microtime(true);
		$that = self::getInstance();
		if ($app_name !== null)
			$this->setAppName($app_dir);
		$that->setAppDir($app_dir);
		$that->init();
		$that->dispatch();
	}

	public static function getAppName()
	{
		return self::getInstance()->app_name;
	}

	public static function logExecutionTime()
	{
		error_log("execution time: ".round(microtime(true) - self::$start, 4)." seconds", 0);
	}

	public static function exposePHPInfo()
	{
		self::$expose_php_info = true;
	}

	public static function PHPisExposed()
	{
		return (self::$expose_php_info === true);
	}
}
?>